Below is an example of implementing a simple REST API service using Flask, including basic CRUD operations for a collection of tasks.
from flask import Flask, jsonify, request
app = Flask(__name__)
tasks = [
{
'id': 1,
'title': 'Learn Python',
'done': False
},
{
'id': 2,
'title': 'Build REST API',
'done': False
}
]
@app.route('/tasks', methods=['GET'])
def get_tasks():
return jsonify({'tasks': tasks})
@app.route('/tasks/', methods=['GET'])
def get_task(task_id):
task = next((task for task in tasks if task['id'] == task_id), None)
if task:
return jsonify({'task': task})
else:
return jsonify({'error': 'Task not found'}), 404
@app.route('/tasks', methods=['POST'])
def create_task():
if not request.json or 'title' not in request.json:
return jsonify({'error': 'Title is required'}), 400
task = {
'id': len(tasks) + 1,
'title': request.json['title'],
'done': False
}
tasks.append(task)
return jsonify({'task': task}), 201
@app.route('/tasks/', methods=['PUT'])
def update_task(task_id):
task = next((task for task in tasks if task['id'] == task_id), None)
if not task:
return jsonify({'error': 'Task not found'}), 404
if 'title' in request.json:
task['title'] = request.json['title']
if 'done' in request.json:
task['done'] = request.json['done']
return jsonify({'task': task})
@app.route('/tasks/', methods=['DELETE'])
def delete_task(task_id):
global tasks
tasks = [task for task in tasks if task['id'] != task_id]
return jsonify({'result': True})
if __name__ == '__main__':
app.run(debug=True)
To test the API, you can use tools like curl, Postman, or any HTTP client to interact with the endpoints:
curl http://127.0.0.1:5000/tasks
curl -X POST -H "Content-Type: application/json" -d '{"title":"New Task"}' http://127.0.0.1:5000/tasks
curl -X PUT -H "Content-Type: application/json" -d '{"title":"Updated Task", "done":true}' http://127.0.0.1:5000/tasks/1
curl -X DELETE http://127.0.0.1:5000/tasks/1